//
//  ViewController.m
//  OCR-Example
//
//  Created by nhope on 2018/1/16.
//  Copyright © 2018年 xiaopin. All rights reserved.
//

#import "ViewController.h"
#import <TesseractOCR/TesseractOCR.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Create RecognitionOperation
    G8RecognitionOperation *operation = [[G8RecognitionOperation alloc] initWithLanguage:@"eng+chi_sim"];

    // Configure inner G8Tesseract object as described before
//    operation.tesseract.charWhitelist = @"01234567890";
//    operation.tesseract.image = [[UIImage imageNamed:@"image_sample.jpg"] g8_blackAndWhite];
//    operation.tesseract.image = [[UIImage imageNamed:@"text.png"] g8_blackAndWhite];
//    operation.tesseract.image = [[UIImage imageNamed:@"8055.png"] g8_blackAndWhite];
    operation.tesseract.image = [[self textImage] g8_blackAndWhite];

    // Setup the recognitionCompleteBlock to receive the Tesseract object
    // after text recognition. It will hold the recognized text.
    operation.recognitionCompleteBlock = ^(G8Tesseract *recognizedTesseract) {
        // Retrieve the recognized text upon completion
        NSLog(@"%@", [recognizedTesseract recognizedText]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:recognizedTesseract.recognizedText delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    };

    // Add operation to queue
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
    
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:operation.tesseract.image];
    [self.view addSubview:imageView];
    imageView.center = CGPointMake(200.0, 200.0);
    imageView.backgroundColor = [UIColor orangeColor];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UIImage *)textImage {
//    NSString *text = @"This is English text.";
//    NSString *text = @"0123456789";
//    NSString *text = @"识别中文";
    NSString *text = @"This中文43H5us2语文";
    NSDictionary *attributes = @{
                                 NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0],
                                 NSForegroundColorAttributeName: [UIColor blackColor],
                                 NSBackgroundColorAttributeName: [UIColor whiteColor],
                                 };
    CGRect rect = [text boundingRectWithSize:self.view.bounds.size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    [text drawInRect:rect withAttributes:attributes];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


@end
